/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.autoconfigure;

import io.iec.edp.caf.autoconfigure.spi.AutoConfigurationExclusion;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ServiceLoader;

/**
 * @author wangyandong
 * @date 2021/09/13 16:04
 * @email wangyandong@inspur.com
 */
public class CafApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        //获取所有的自动排除类扩展
        ServiceLoader<AutoConfigurationExclusion> exclusions = ServiceLoader.load(AutoConfigurationExclusion.class);

        //循环获取每个排除类的排除列表
        List<String> excludeList = new ArrayList<>();
        for (AutoConfigurationExclusion exclusion : exclusions) {
            excludeList.addAll(exclusion.exclude());
        }

        if (excludeList.size() <= 0)
            return;

        //组织排除列表，并添加到PropertySource中（cafPropertySource仅为key键，无其它含义）
        String exclude = String.join(", ", excludeList);
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        HashMap map = new HashMap<>();
        map.put("spring.autoconfigure.exclude", exclude);
        MapPropertySource customSource = new MapPropertySource("cafPropertySource", map);
        propertySources.addFirst(customSource);
    }
}